package com.uduemc.biso.node.module.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.core.extities.center.SysSystemType;
import com.uduemc.biso.core.utils.RedisUtil;
import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.backend.feign.WebBackendFeign;
import com.uduemc.biso.node.core.property.GlobalProperties;
import com.uduemc.biso.node.core.utils.RestResultUtil;
import com.uduemc.biso.node.module.service.SysSystemTypeService;

@Service
public class SysSystemTypeServiceImpl implements SysSystemTypeService {

	@Autowired
	private WebBackendFeign webBackendFeign;

	@Autowired
	private GlobalProperties globalProperties;

	@Autowired
	private RedisUtil redisUtil;

	@Override
	public SysSystemType findOne(long id)
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		List<SysSystemType> all = findAll();
		if (CollectionUtils.isEmpty(all)) {
			return null;
		}
		for (SysSystemType item : all) {
			if (item.getId().longValue() == id) {
				return item;
			}
		}
		return null;
	}

	@Override
	public List<SysSystemType> findAll()
			throws JsonParseException, JsonMappingException, JsonProcessingException, IOException {
		String KEY = globalProperties.getRedisKey().getSystemType();
		@SuppressWarnings("unchecked")
		List<SysSystemType> cache = (ArrayList<SysSystemType>) redisUtil.get(KEY);
		if (CollectionUtils.isEmpty(cache)) {
			RestResult restResult = webBackendFeign.getSystemTypeInfos();
			@SuppressWarnings("unchecked")
			List<SysSystemType> data = (List<SysSystemType>) RestResultUtil.data(restResult,
					new TypeReference<ArrayList<SysSystemType>>() {
					});
			return data;
		}
		return cache;
	}

}
